package jsp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月03日13:54
 */

@WebServlet("*.cookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path=request.getServletPath();
        if("/add.cookie".equals(path)){
            addCookie(request,response);
        }
        if("/findAll.cookie".equals(path)){
            findAll(request,response);
        }
        if("/modify.cookie".equals(path)){
            modifyCookie(request,response);
        }
        if("/deleteCookie.cookie".equals(path)){
            deleteCookie(request,response);
        }
    }

    public void addCookie(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        //创建一个Cookie对象
        Cookie cookie=new Cookie("username","abc");
        Cookie cookie2=new Cookie("password","123");

        // Cookie的构造函数中,其值只支持字符串
        // 因此,Cookie中只能保存字符串
        // 且Cookie只支持ISO-8859-1的字符集
        // 如果保存了非ISO-8859-1的中文字符,会报错
        // Cookie cookie3=new Cookie("name","管理员");
        String name=URLEncoder.encode("管理员","UTF-8");

        Cookie cookie3=new Cookie("name",name);
        //将创建的cookie添加到响应对象中

        response.addCookie(cookie);
        response.addCookie(cookie2);
        response.addCookie(cookie3);
    }
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie:cookies){
            //如果需要获取到原始的字符集的数据，需要通过URLDecoder进行解码获取
            System.out.println(cookie.getName()+":"+ URLDecoder.decode(cookie.getValue(),"UTF-8"));
        }
    }
    public void modifyCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie cookie=new Cookie("username","alice");
        Cookie cookie2=new Cookie("password","11111");
        response.addCookie(cookie);
        response.addCookie(cookie2);
    }
    public void deleteCookie(HttpServletRequest request, HttpServletResponse response){

        //在Cookie中，可以设置Cookie的生存时间，当超出生存时间后，cookie自动移除
        Cookie cookie=new Cookie("username","jack");

        //指定cookie生存时间
        cookie.setMaxAge(100);
        Cookie cookie2=new Cookie("password","222222");

        //当设置为0，表示删除指定cookie
        //由于key的值相同，会副高原来的cookie
        // 所以想要删除某一个cookie，只需要添加一个新的cookie，时间设置为0
        cookie2.setMaxAge(0);
        response.addCookie(cookie);
        response.addCookie(cookie2);

    }
}
